package com.common.sdk.net.connect.http.util;

import com.android.sohu.sdk.common.toolbox.LogUtils;
import com.android.sohu.sdk.common.toolbox.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by chengjiangsang116630 on 2018/2/6.
 */

public class SohuRequestBuilder {

    private static Map<String, Object> baseParams = new HashMap<>();

    public static void init(Map<String, Object> baseParams) {
        SohuRequestBuilder.baseParams.putAll(baseParams);
    }

    public static void setBaseParam(String key, Object value) {
        SohuRequestBuilder.baseParams.put(key, value);
    }

    public static Request addTag(Request request, Object tag) {
        if (tag != null) {
            request = request.newBuilder().tag(tag).build();
        }
        return request;
    }

    public static Request addQueryParam(Request request, String key, Object value) {
        if (value != null) {
            HttpUrl url = request.url();
            if (url != null) {
                request = request.newBuilder().url(url.newBuilder().addQueryParameter(key, value.toString()).build()).build();
            }
        }
        return request;
    }

    public static Request setQueryParam(Request request, String key, Object value) {
        if (value != null) {
            HttpUrl url = request.url();
            if (url != null) {
                request = request.newBuilder().url(url.newBuilder().setQueryParameter(key, value.toString()).build()).build();
            }
        }
        return request;
    }

    public static Request addHeaderParam(Request request, String key, Object value) {
        if (value != null) {
            Headers headers = request.headers();
            if (headers == null) {
                headers = new Headers.Builder().build();
            }
            request = request.newBuilder().headers(headers.newBuilder().add(key, value.toString()).build()).build();
        }
        return request;
    }

    public static Request setHeaderParam(Request request, String key, Object value) {
        if (value != null) {
            Headers headers = request.headers();
            if (headers == null) {
                headers = new Headers.Builder().build();
            }
            request = request.newBuilder().headers(headers.newBuilder().set(key, value.toString()).build()).build();
        }
        return request;
    }

    public static Request buildGetRequestNoBaseParams(String url, Map<String, Object> queryParams, Map<String, Object> headers) {
        return buildGetRequest(url, queryParams, headers, false);
    }

    public static Request buildGetRequest(String url, Map<String, Object> queryParams, Map<String, Object> headers) {
        return buildGetRequest(url, queryParams, headers, true);
    }

    private static Request buildGetRequest(String url, Map<String, Object> queryParams, Map<String, Object> headers, boolean needBase) {
        try {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            HttpUrl httpUrl = HttpUrl.parse(url);
            if (httpUrl == null) {
                return null;
            }
            HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
            Headers.Builder headersBuilder = new Headers.Builder();

            if (needBase) {
                if (baseParams != null && baseParams.size() > 0) {
                    Set<String> keys = baseParams.keySet();
                    Iterator<String> it = keys.iterator();
                    while (it.hasNext()) {
                        String key = it.next();

                        // 如果请求参数中包含基础参数，则以请求参数为准
                        if (queryParams != null && queryParams.size() > 0) {
                            if (queryParams.keySet().contains(key)) {
                                continue;
                            }
                        }

                        Object value = baseParams.get(key);
                        if (value != null) {
                            urlBuilder.addQueryParameter(key, value.toString());
                        }
                    }
                }
            }

            if (queryParams != null && queryParams.size() > 0) {
                Set<String> keys = queryParams.keySet();
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    Object value = queryParams.get(key);
                    if (value != null) {
                        urlBuilder.addQueryParameter(key, value.toString());
                    }
                }
            }

            // TODO 把构建header的方法提取出来
            if (headers != null && headers.size() > 0) {
                Set<String> keys = headers.keySet();
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    Object value = headers.get(key);
                    if (value != null) {
                        String strValue = value.toString();
                        strValue = strValue.replaceAll("[^\\u001f-\\u007f\t]+", "");
                        headersBuilder.add(key, strValue);
                    }
                }
            }

            Request request = new Request.Builder()
                    .url(urlBuilder.build()).get()
                    .headers(headersBuilder.build())
                    .build();
            return request;
        } catch (Exception | Error e) {
            LogUtils.e(e);
            return null;
        }
    }

    public static Request buildGetRequest(String url, Map<String, Object> queryParams) {
        return buildGetRequest(url, queryParams, null);
    }

    public static Request buildPostRequest(String url, Map<String, Object> postParams) {
        return buildPostRequest(url, postParams, null);
    }

    public static Request buildPostRequestNoBaseParams(String url, Map<String, Object> postParams, Map<String, Object> headers) {
        return buildPostRequest(url, postParams, headers, false);
    }

    public static Request buildPostRequest(String url, Map<String, Object> postParams, Map<String, Object> headers) {
        return buildPostRequest(url, postParams, headers, true);
    }

    private static Request buildPostRequest(String url, Map<String, Object> postParams, Map<String, Object> headers, boolean needBase) {
        try {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            HttpUrl httpUrl = HttpUrl.parse(url);
            if (httpUrl == null) {
                return null;
            }
            FormBody.Builder builder = new FormBody.Builder();
            Headers.Builder headersBuilder = new Headers.Builder();

            if (needBase) {
                if (baseParams != null && baseParams.size() > 0) {
                    Set<String> keys = baseParams.keySet();
                    Iterator<String> it = keys.iterator();
                    while (it.hasNext()) {
                        String key = it.next();
                        // 如果请求参数中包含基础参数，则以请求参数为准
                        if (postParams != null && postParams.size() > 0) {
                            if (postParams.keySet().contains(key)) {
                                continue;
                            }
                        }
                        Object value = baseParams.get(key);
                        if (value != null) {
                            builder.add(key, value.toString());
                        }
                    }
                }
            }

            if (postParams != null && postParams.size() > 0) {
                Set<String> keys = postParams.keySet();
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    Object value = postParams.get(key);
                    if (value != null) {
                        builder.add(key, value.toString());
                    }
                }
            }

            if (headers != null && headers.size() > 0) {
                Set<String> keys = headers.keySet();
                Iterator<String> it = keys.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    Object value = headers.get(key);
                    if (value != null) {
                        String strValue = value.toString();
                        strValue = strValue.replaceAll("[^\\u001f-\\u007f\t]+", "");
                        headersBuilder.add(key, strValue);
                    }
                }
            }

            RequestBody requestBody = builder.build();

            Request request = new Request.Builder()
                    .url(httpUrl)
                    .headers(headersBuilder.build())
                    .post(requestBody)
                    .build();
            return request;
        } catch (Exception | Error e) {
            LogUtils.e(e);
            return null;
        }
    }

}
